package angels.client.Tasks;

import java.net.HttpURLConnection;
import java.util.TimerTask;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import angels.client.Entities.Sharing;
import angels.client.Helpers.JSONHelper;
import angels.client.Services.BusyHourService;

public class SampleTrafficTask extends TimerTask {
	private DefaultHttpClient client;
	private final BusyHourService service;
	
	public SampleTrafficTask(BusyHourService service) {
		this.service = service;
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        client = new DefaultHttpClient(httpParameters);
	}
	
	@Override
    public void run() {
		try {
			HttpGet request = new HttpGet(service.getRobotsURL(service.category,service.subcategory));
			HttpResponse response = client.execute(request);
			
			if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK)
			    return;
			
			JSONObject json_response;
						
			Sharing[] robots=null;
						
			if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){
				json_response = JSONHelper.parseJSONResponse(response);
				JSONArray json_robots = json_response.getJSONArray("robots");
				if (json_robots.length()!=0){
					robots = new Sharing[json_robots.length()];
					for (int i = 0; i < json_robots.length(); i++)
					    robots[i] = new Sharing(json_robots.getJSONObject(i));
				}
			} 
			// notify service of results
			if (robots!=null)
			{
				service.notifyTraffic(robots);
			}
			service.notifyTraffic(robots);
		} catch (Exception e) {
		}
	}
}